/*设置全局变量*/
var igon = ["attributes", "parent", "count", "at", "each", "text"];
var path, method, query, body, _token;
var url = require('url');
var querystring = require('querystring');
var xmlreader = require('xmlreader');
var get = require('./get')
//默认过滤请求类型
var defaultFilter = '/controller/wechat';
//默认消息处理
var msgHandler = require('./msgControl');
var util = require('./fixData');
var outPut = require('./output');
var config = require('../config.js');

//定时更新acess-token
var access_token;
var expires;
getAccesstoken();
var schedule = require('node-schedule');
var rule = new schedule.RecurrenceRule();
rule.minute = [0, 120];
schedule.scheduleJob(rule, function() {
	getAccesstoken();
});
/*
 * 处理入口
 */
module.exports.process = function(req, res, handler, filter) {
	path = url.parse(req.url).pathname;
	filter = filter || defaultFilter;
	res.writeHead(200, {
		'Content-Type': 'text/plain'
	});
	if (path.indexOf(filter) != 0) {
		res.end(path);
		return;
	}
	method = req.method;
	query = querystring.parse(req.url.split("?")[1]);
	msgHandler = handler || msgHandler;
	_token = path.replace(filter, config.token);

	// 处理请求
	if (method == "GET") {
		doGet(res);
	} else {
		body = '';
		req.setEncoding('utf8');
		req.addListener('data', function(chunk) {
			body += chunk;
		});
		req.addListener('end', function() {
			doPost(res);
		});
	}
};

function doGet(res) {
	console.log('doGet');
	if (checkSignature()) {
		res.end(query.echostr);
	} else {
		res.end("signature error");
	}
}

function doPost(res) {
	console.log("doPost");
	xmlreader.read(body, function(errors, response) {
		if (null !== errors) {
			console.log(errors);
			return;
		}
		var msg = {};
		for (var k in response.xml) {
			if (igon.indexOf(k) == -1) {
				if (response.xml[k] && response.xml[k].text) {
					msg[k] = response.xml[k].text.call();
				}
			}
		}
		var callback;
		if (msg.MsgType == "event") {
			msgHandler['test'];
		}
		if (msg.MsgType == "text") {
			msgHandler['test'];
		}

		function sendMsg(callback) {
			if (callback && typeof callback == "function") {
				callback.call(msg, new outPut(res, msg));
			} else {
				res.end("signature error in doPost");
			}
		}

	});
}

/*
 * 签名认证
 */
function checkSignature() {
	var params = [_token, query.timestamp, query.nonce];
	var signature = query.signature;
	params = params.sort();
	var temp = params[0] + params[1] + params[2];
	var crypto = require('crypto');
	var sha1 = crypto.createHash('sha1');
	sha1.update(temp)
	var hex = sha1.digest('hex');
	return (hex === signature);
}

/**获取ACCESS-TOKEN**/
function getAccesstoken() {
	get.main({
		url: 'https://api.weixin.qq.com/cgi-bin/token',
		form: {
			grant_type: "client_credential",
			appid: config.appid,
			secret: config.secret
		}
	}, function(err, res, body) {
		if (!err && res.statusCode == 200) {
			var info = JSON.parse(body);
			access_token = info.access_token;
			expires = info.expires_in;
		}
	});
}

module.exports.access_token = access_token;
module.exports.expires = expires;